<template>
  <div class="showQuestion"> 
    <div class="affix-container">      
      <el-affix :offset="70">
        <el-popover
          placement="left-start"
          title="您已选题目："
          :width="950"
          trigger="hover"
        >
          <template #reference>
            <el-badge :value="state.selectQuestionList.length" class="item">
              <el-button :icon="ShoppingCart" size="large" circle/> 
            </el-badge>
          </template>
          <el-table ref="multipleTableRef" class="tableClass" :data="state.selectQuestionList" stripe
            max-height="300"            
            :row-style="{height:50+'px'}" 
	          :cell-style="{padding:0+'px'}" 
            :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
            :row-key="getRowKeys"
            @selection-change="handleSelectionChange" border
          >
            <el-table-column type="selection" width="35" />
            <el-table-column type="index" width="45" label="序" />
            <el-table-column width="500" property="content" label="内容" show-overflow-tooltip="true" />
            <el-table-column width="100" property="answer" label="答案" show-overflow-tooltip="true" />
            <el-table-column width="200" property="explain" label="解析" show-overflow-tooltip="true" />
            <el-table-column align="right" width="50">
              <template #header>
                <el-icon @click="handeleMultiDelete()"><DeleteFilled /></el-icon>
              </template>
              <template #default="scope">                         
                <el-icon style="width: 1em; height: 1em; margin-right: 1px" @click="handleDelete(scope.$index)">
                  <RemoveFilled />
                </el-icon>
              </template>
            </el-table-column>
          </el-table>
        </el-popover>
      </el-affix> 
   
    </div>  
    <div class="header" v-show="state.isGetQuestionsByKnowledgepoint">
      <el-button type="primary" :icon="Plus" @click="addOneQuestion" >录入单题</el-button>
    </div>
    <div  class="questionsBody" id="questionsBodyRef" ></div>
    <div v-if="noQuestionList">{{ state.error }} </div>
    <div v-else>
    <template v-for="item in state.questionList" :key="item.id">
      <el-card class="box-card">
          <template #header>
              <div class="card-header">
                  <span>题型：{{item.type}}</span>
                  <span>难度：{{ item.difficulty_level }}</span>
                  <span>创建者：{{ item.owner_name }}</span>
                  <span>日期：{{ onlyDate(item.add_time ) }}</span>
                  <span>来源：{{ item.reference }}</span>
                  <el-button type="primary" :icon="Plus" @click="addToCart(item)" >加入</el-button>
              </div>
        </template>
        <div class="card-body">       
            <div v-html="item.content" class="line-break"></div> 
        </div>
      </el-card>
    </template>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        @current-change="changePage"
      />
    </div>
  </div>
</template>

<script setup>
  import { reactive, ref, onMounted, onUnmounted, computed } from 'vue'
  import { Plus, ShoppingCart,Delete } from '@element-plus/icons-vue'
  import axios from '@/utils/axios'
  import { useRoute, useRouter } from 'vue-router'
  const multipleTableRef = ref()
	const select_order_number = ref('') //表格select选中的条数
  const select_orderId = ref([]) //表格select复选框选中的id
  const multipleSelection = ref([])  
  const route = useRoute()
  const router = useRouter()
  const noQuestionList = computed(()=>{
    return state.total == 0 || state.questionList.length==0
  })  
  //为了让前端的代码更易理解，这里做后端api名称映射
  const apiNameMap = {
    getQuestionsByCourse : '/ChapterContainQuestionViewSet',
    getQuestionsByChapter : '/SectionContainQuestions',
    getQuestionsBySection : '/KnowledgeContainQuestions',
    getQuestionsByKnowledgepoint : '/questions',
  }
  //为了让前端的代码更易理解，这里做名称映射，后端的api参数
  const apiRangeMap = {
    getQuestionsByCourse : 'course',
    getQuestionsByChapter : 'chapter',
    getQuestionsBySection : 'section',
    getQuestionsByKnowledgepoint : 'knowledgepoint',
  }

  const state = reactive({
    loading: false, // 列表数据接口返回前的 loading
    questionList: [], // 数据列表
    total: 0, // 总条数
    currentPage: 0, // 当前页
    pageSize: 10, // 分页大小
    id: -1,
    apiName : "",    //后端api名称
    range: "",      //所有题目的大范围，比如按章、节、课程等
    isGetQuestionsByKnowledgepoint: false,  //是否按照知识点搜索题目，方便判断录入题目
    knowledgepointId: -1,
    selectQuestionList: [],
  })
  //监听路由变化
  const unWatch = router.beforeEach((to, from, next) => { 
    state.apiName = apiNameMap[to.name]
    state.range = apiRangeMap[to.name]
    const {id} = to.query
    state.id = id    
    state.currentPage = 1
    selectFunction(to.name)
    if (to.name ==="getQuestionsByKnowledgepoint"){
      state.isGetQuestionsByKnowledgepoint = true
      state.knowledgepointId = id
    }
    next(true)
  })
  
  //初始化  
  onMounted(()=>{
    console.log("第一次加载showQuestion的onMounted")
    state.apiName = apiNameMap[route.name]
    state.range = apiRangeMap[route.name]
    const {id} = route.query
    state.id = id
    state.currentPage = 1
    selectFunction(route.name)
  })
  onUnmounted(()=>{
    console.log("销毁路由监听")
    unWatch()
  })
  //根据当前路由名选择执行相应的函数，请求不同的后端apiName
  const selectFunction = (name)=>{
    switch(name){
        case 'getQuestionsByCourse':
            getQuestionsByCourse();
            break;
        case 'getQuestionsByChapter':
            getQuestionsByChapter();
            break;
        case 'getQuestionsBySection':
            getQuestionsBySection();
            break;
        case 'getQuestionsByKnowledgepoint':
            getQuestionsByKnowledgepoint();
            break;
        case 'index': 
            getQuestionsHome();
            break;
    }
  }
  // 某一册下的所有题目
  const getQuestionsByCourse =()=>{       
    state.loading = true
    axios.get(state.apiName,{
      params:{
        page: state.currentPage,
        course: state.id
      }
    }).then(res => {
      if (res.code==200){
        state.questionList = res.data.data
        state.loading = false
        state.total=res.data.count        
      }else{        
        state.total=0
        state.error = res.message
        if (res.code==419){
          router.push("/login")
        }
      }
    })
    .catch((error)=>{
      console.log("error")
    })   
  }
    // 某章下的所有题目
  const getQuestionsByChapter =()=>{
    state.loading = true
    axios.get(state.apiName,{
      params:{
        page: state.currentPage,
        chapter: state.id
      }
    }).then(res => {
      if (res.code==200){
        state.questionList = res.data.data
        state.loading = false
        state.total=res.data.count        
      }else{
        console.log("error", res.message)
        state.total=0
        state.error = res.message
      }
    })
    .catch((error)=>{
      console.log("error")
    })   
  }
  // 某节下的所有题目
  const getQuestionsBySection =()=>{
    state.loading = true
    axios.get(state.apiName,{
      params:{
        page: state.currentPage,
        section: state.id
      }
    }).then(res => {
      if (res.code==200){
        state.questionList = res.data.data
        state.loading = false
        state.total=res.data.count        
      }else{
        console.log("error", res.message)
        state.total=0
        state.error = res.message
      }
    })
    .catch((error)=>{
      console.log("error")
    })   
  }
  // 一个知识点下的所有题目
  const getQuestionsByKnowledgepoint = () => {
    state.loading = true
    axios.get(state.apiName,{
      params:{
        page: state.currentPage,
        knowledgepoint: state.id
      }
    }).then(res => {
      if (res.code==200){        
        state.questionList = res.data.results
        state.loading = false
        state.total=res.data.count
      }else{
        console.log("error", res.message)
        state.total=0
        state.error = res.message
      }        
    })
    .catch((error)=>{
      console.log("error")
    })  
  } 
  const getQuestionsHome = () => {    
    axios.get('/questions',{
      params:{
        page: state.currentPage,
      }
    }).then(res => {
      if (res.code==200){        
        state.questionList = res.data.results
        state.loading = false
        state.total=res.data.count
      }else{
        console.log("error", res.message)
        state.total=0
        state.error = res.message
      }        
    })
    .catch((error)=>{
      console.log("error")
    })  
  } 
  const addOneQuestion=()=>{
    router.push({path :"/addQuestion" ,query: { knowledgepointId: state.knowledgepointId}})
  }
  const changePage = (val)=>{
    state.currentPage = val
    selectFunction()
    document.querySelector('#questionsBodyRef').scrollIntoView(true);
  }
  //截取时间中的日期
  const onlyDate = (datastr)=>{
      return datastr.slice(0,10)
  }
  const addToCart = (item)=>{
    state.selectQuestionList.push(item)
  }
  const handleDelete = (index) => {
    state.selectQuestionList.splice(index,1)
  }
  const handeleMultiDelete = ()=>{ 
    for (const i in select_orderId.value){
      console.log("i的值:",i)
        state.selectQuestionList.splice(i, 1)
    }
  }
  //选中的list
  const getRowKeys = (row) => {
      //记录每行的key值
      return row.id;
    }
//当表格选择项发生变化时会触发该事件
  const handleSelectionChange = (val) => {
      // 解决来回切换页面，也无法清除上次选中情况
      multipleSelection.value = val;
      select_order_number.value = multipleSelection.value.length;
      select_orderId.value = [];   //清空，再遍历加入
      if (val) {
        val.forEach((row) => {
          if (row) {  
            select_orderId.value.push(row.id);
          }
        });
      }
      console.log(select_orderId.value);
    }
</script>


<style scoped>
  .showQuestion{
    margin: 0;
  }
  .header {
    display: block;
    margin: 5;
  }
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 10px;
    margin: 0;
    padding: 0;
    height: 10px;
  }
  .card-body {
      display: block;
      margin: 0px;
      padding: 0px;
  }
  .text {
    font-size: 10px;
  }
  .item {
    margin-bottom: 18px;
  }
  .box-card {
    height:auto;
    overflow-y: auto;
  }
  .line-break{
  white-space: pre-wrap;
  }
  img{
      display:block;
  }
  .affix-container{
    text-align: right;
    margin: 0px 50px;
  }
  
.tableClass .cell{   
    padding: 0!important;
    height: 20px!important;
    line-height: 20px!important;
    text-align: center;
    font-size: 10px;
  }
</style>